﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mvp.DTO;
using Mvp.Task;

namespace Mvp.Presenter
{
    /*
     * 上面的代码是很直白的,只有一个主题思想：
     * 从task中获取数据,然后调用view接口的属性,
     * 或者从view接口获得DropDownList的引用(通过ILookupList),然后通过BindTo()方法为列表填充数据。
     * 注意到Initialize()方法,它为列表填充数据,这个应该在页面加载之前就被调用；
     * 还有DisplayBookDetails()方法,它应该在列表的SelectedIndexChanged事件被触发时调用,
     * 所以我们还有最后一部没有做,再次修改Default.aspx.cs文件,设置这些方法的触发时机。
     */

    public class ViewBookPresenter
    {
        private readonly IViewBook _view;
        private readonly IBookTask _task;

        public ViewBookPresenter(IViewBook view,IBookTask task)
        {
            _view = view;
            _task = task;
        }

        public ViewBookPresenter(IViewBook view)
            :this(view,new SimpleBookTask())
        {

        }

        /// <summary>
        /// 初始化方法: 绑定列表
        /// </summary>
        public void Initialize()
        {
            ILookupCollection collection = _task.GetBookList();
            collection.BindTo(_view.BookList);
            DisplayBookDetails();
        }

        private int? SectectBookID
        {
            get
            {
                int? id = null;
                string selectID = _view.BookList.SelectedItem.Value;

                if (!string.IsNullOrEmpty(selectID))
                {
                    try
                    {
                        id = int.Parse(selectID.Trim());
                    }
                    catch (FormatException){}
                }

                return id;
            }
        }

        public void DisplayBookDetails()
        {
            int? bookID = SectectBookID;
            if (bookID.HasValue)
            {
                BookDTO book = _task.GetDetailsForBook(bookID.Value);
                UpdateViewFrom(book);
            }
        }

        private void UpdateViewFrom(BookDTO book)
        {
            _view.BookTitle = book.Title;
            _view.PubDate = string.Format(new DateFomatter(), "{0}", book.PubDate);
            _view.Price = book.Price.ToString();
        }

        private class DateFomatter : ICustomFormatter,IFormatProvider{

            #region ICustomFormatter 成员

            public string Format(string format, object arg, IFormatProvider formatProvider)
            {
                DateTime date = (DateTime)arg;
                return string.Format("{0}年{1}月{2}日", date.Year, date.Month, date.Day);
            }

            #endregion

            #region IFormatProvider 成员

            public object GetFormat(Type formatType)
            {
                return this;
            }

            #endregion
        }
    }
}
